﻿using System;
using System.Collections.Generic;
using System.Data;
using Agile.Service;
using Microsoft.AspNetCore.Mvc;

namespace Web.Areas.Sys.Controllers {
    ///<summary>
    ///计划任务
    ///</summary>
    [Area("Sys")]
    public class ScheduleTaskController : BaseController<ScheduleTask> {
        private readonly IScheduleTaskService _scheduleTaskService;
        public ScheduleTaskController(IScheduleTaskService scheduleTaskService) {
            _scheduleTaskService = scheduleTaskService;
        }

        public virtual IActionResult RunNow(string keyValue) {
            try {
                var scheduleTask = _scheduleTaskService.Find(keyValue)
                                   ?? throw new ArgumentException("Schedule task cannot be loaded", nameof(keyValue));

                //ensure that the task is enabled
                var task = new AgileTask(scheduleTask) { Enabled = true };
                task.Execute(true, false);

            } catch (Exception exc) {
                Logger.LogError("ScheduleTaskController->RunNow",exc);
            }
            return RedirectToAction("List");
        }
        [HttpPost]
        public virtual IActionResult RunTask(string taskType) {
            var scheduleTask = _scheduleTaskService.GetTaskByType(taskType);
            if (scheduleTask == null)
                //schedule task cannot be loaded
                return NoContent();

            var task = new AgileTask(scheduleTask);
            task.Execute();

            return NoContent();
        }
    }
}
